package com.jmb.api.common.center;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson2.JSONObject;
import com.jmb.api.common.exception.ValidUtilException;

import com.jmb.api.common.result.SqlType;
import com.jmb.api.common.utils.JdbcUtil;
import lombok.extern.slf4j.Slf4j;

import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.yaml.snakeyaml.Yaml;


import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 反射不支持spring ioc
 * 我这里使用new的方式创建对象
 */
@Slf4j
public class EnvWithoutSpring {

    /**
     * 根据数据源编号 运行环境 返回连接信息
     * @param dbId 数据源编号
     * @param runEnv 运行环境 0dev 1test 2stg 3prod 4debug
     * @return 连接信息
     */
    public DbCenter datasource(Long dbId, Integer runEnv) {
        String sql = "select `id`,`name`,`type`,`description`,`url`,`username`,`password`,`created_time`,`update_time`,`status`,\n" +
                "        `dev_url`,`dev_username`,`dev_password`,`test_url`,`test_username`,`test_password`,`stg_url`,`stg_username`,\n" +
                "        `stg_password`,`prod_url`,`prod_username`,`prod_password`\n" +
                "        from `t_db` where `id` = " + dbId;
        try(DruidDataSource druid = connection()) {
            JdbcTemplate template = new JdbcTemplate(druid);
            DbDo db = template.queryForObject(sql, new Object[]{dbId}, new BeanPropertyRowMapper<>(DbDo.class));
            if (db == null){
                throw new ValidUtilException("未找到该数据源");
            }
            Integer status = db.getStatus();
            if (status == 1){
                log.warn("该数据源已禁用，dbName= {}",db.getName());
                throw new ValidUtilException("该数据源已禁用");
            }
            String url;
            String username;
            String password;
            switch (runEnv){
                case 4 :
                    url = db.getUrl();
                    username = db.getUsername();
                    password = db.getPassword();
                    break;
                case 0 :
                    url = db.getDevUrl();
                    username = db.getDevUsername();
                    password = db.getDevPassword();
                    break;
                case 1 :
                    url = db.getTestUrl();
                    username = db.getTestUsername();
                    password = db.getTestPassWord();
                case 2 :
                    url = db.getStgUrl();
                    username = db.getStgUsername();
                    password = db.getStgPassword();
                    break;
                case 3 :
                    url = db.getProdUrl();
                    username = db.getProdUsername();
                    password = db.getProdPassword();
                    break;
                default:
                    throw new ValidUtilException("数据源确定运行环境时出错,运行环境不存在");
            }
            if (url == null || username == null || password == null){
                throw new ValidUtilException("配置缺失，请确认对应环境下的URL、用户名及密码未设置");
            }
            DbCenter center = new DbCenter();
            center.setUrl(url);
            center.setUsername(username);
            center.setPassword(password);
            return center;

        } catch (Exception e) {
            log.error("数据源连接失败 {}",e.getMessage());
            throw new ValidUtilException("数据源连接失败"+e.getMessage());
        }
    }

    /**
     * 获取数据库连接池
     * @return alex数据库连接池
     * @throws Exception 异常
     */
    private DruidDataSource connection() throws Exception {
        Yaml yaml = new Yaml();
        ClassPathResource resource = new ClassPathResource("application.yml");
        try (InputStream fis = resource.getInputStream()) {
            JSONObject yamlConfig = yaml.loadAs(fis, JSONObject.class);
            JSONObject db = yamlConfig.getJSONObject("spring").getJSONObject("datasource");
            String url_ = db.getString("url");
            String username_ = db.getString("username");
            String password_ = db.getString("password");
            return JdbcUtil.getDruidDataSource(url_, username_, password_, SqlType.SELECT);
        }
    }

}
